﻿// Decompiled with JetBrains decompiler
// Type: TaleWorlds.CampaignSystem.Issues.NearbyBanditBaseIssueBehavior
// Assembly: TaleWorlds.CampaignSystem, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: E85F8C15-4DF6-4E9C-A58A-29177E40D07A
// Assembly location: D:\steam\steamapps\common\Mount & Blade II Bannerlord\bin\Win64_Shipping_Client\TaleWorlds.CampaignSystem.dll

using Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using TaleWorlds.CampaignSystem.Actions;
using TaleWorlds.CampaignSystem.CharacterDevelopment;
using TaleWorlds.CampaignSystem.Conversation;
using TaleWorlds.CampaignSystem.MapEvents;
using TaleWorlds.CampaignSystem.Party;
using TaleWorlds.CampaignSystem.Roster;
using TaleWorlds.CampaignSystem.Settlements;
using TaleWorlds.Core;
using TaleWorlds.Library;
using TaleWorlds.Localization;
using TaleWorlds.ObjectSystem;
using TaleWorlds.SaveSystem;

#nullable disable
namespace TaleWorlds.CampaignSystem.Issues
{
  public class NearbyBanditBaseIssueBehavior : CampaignBehaviorBase
  {
    private const int NearbyHideoutMaxRange = 35;
    private const IssueBase.IssueFrequency NearbyHideoutIssueFrequency = IssueBase.IssueFrequency.VeryCommon;

    private Settlement FindSuitableHideout(Hero issueOwner)
    {
      Settlement suitableHideout = (Settlement) null;
      float num1 = float.MaxValue;
      foreach (Hideout hideout in Campaign.Current.AllHideouts.Where<Hideout>((Func<Hideout, bool>) (t => t.IsInfested)))
      {
        float num2 = hideout.Settlement.GatePosition.DistanceSquared(issueOwner.GetMapPoint().Position2D);
        if ((double) num2 <= 1225.0 && (double) num2 < (double) num1)
        {
          num1 = num2;
          suitableHideout = hideout.Settlement;
        }
      }
      return suitableHideout;
    }

    private void OnCheckForIssue(Hero hero)
    {
      if (!hero.IsNotable)
        return;
      Settlement suitableHideout = this.FindSuitableHideout(hero);
      if (this.ConditionsHold(hero) && suitableHideout != null)
        Campaign.Current.IssueManager.AddPotentialIssueData(hero, new PotentialIssueData(new PotentialIssueData.StartIssueDelegate(this.OnIssueSelected), typeof (NearbyBanditBaseIssueBehavior.NearbyBanditBaseIssue), IssueBase.IssueFrequency.VeryCommon, (object) suitableHideout));
      else
        Campaign.Current.IssueManager.AddPotentialIssueData(hero, new PotentialIssueData(typeof (NearbyBanditBaseIssueBehavior.NearbyBanditBaseIssue), IssueBase.IssueFrequency.VeryCommon));
    }

    private IssueBase OnIssueSelected(in PotentialIssueData pid, Hero issueOwner)
    {
      return (IssueBase) new NearbyBanditBaseIssueBehavior.NearbyBanditBaseIssue(issueOwner, pid.RelatedObject as Settlement);
    }

    private bool ConditionsHold(Hero issueGiver)
    {
      return issueGiver.IsHeadman && issueGiver.CurrentSettlement != null && (double) issueGiver.CurrentSettlement.Village.Bound.Town.Security <= 50.0;
    }

    private void OnIssueUpdated(
      IssueBase issue,
      IssueBase.IssueUpdateDetails details,
      Hero issueSolver = null)
    {
      if (!(issue is NearbyBanditBaseIssueBehavior.NearbyBanditBaseIssue nearbyBanditBaseIssue) || details != IssueBase.IssueUpdateDetails.IssueFinishedByAILord)
        return;
      foreach (MobileParty party in (List<MobileParty>) nearbyBanditBaseIssue.TargetHideout.Parties)
        party.Ai.SetMovePatrolAroundSettlement(nearbyBanditBaseIssue.TargetHideout);
    }

    public override void RegisterEvents()
    {
      CampaignEvents.OnCheckForIssueEvent.AddNonSerializedListener((object) this, new Action<Hero>(this.OnCheckForIssue));
      CampaignEvents.OnIssueUpdatedEvent.AddNonSerializedListener((object) this, new Action<IssueBase, IssueBase.IssueUpdateDetails, Hero>(this.OnIssueUpdated));
    }

    public override void SyncData(IDataStore dataStore)
    {
    }

    public class NearbyBanditBaseIssue : IssueBase
    {
      private const int AlternativeSolutionFinalMenCount = 10;
      private const int AlternativeSolutionMinimumTroopTier = 2;
      private const int AlternativeSolutionCompanionSkillThreshold = 120;
      private const int AlternativeSolutionRelationRewardOnSuccess = 5;
      private const int AlternativeSolutionRelationPenaltyOnFail = -5;
      private const int IssueOwnerPowerBonusOnSuccess = 5;
      private const int IssueOwnerPowerPenaltyOnFail = -5;
      private const int SettlementProsperityBonusOnSuccess = 10;
      private const int SettlementProsperityPenaltyOnFail = -10;
      private const int IssueDuration = 15;
      private const int QuestTimeLimit = 30;
      [SaveableField(100)]
      private readonly Settlement _targetHideout;
      [SaveableField(101)]
      private Settlement _issueSettlement;

      internal static void AutoGeneratedStaticCollectObjectsNearbyBanditBaseIssue(
        object o,
        List<object> collectedObjects)
      {
        ((MBObjectBase) o).AutoGeneratedInstanceCollectObjects(collectedObjects);
      }

      protected override void AutoGeneratedInstanceCollectObjects(List<object> collectedObjects)
      {
        base.AutoGeneratedInstanceCollectObjects(collectedObjects);
        collectedObjects.Add((object) this._targetHideout);
        collectedObjects.Add((object) this._issueSettlement);
      }

      internal static object AutoGeneratedGetMemberValue_targetHideout(object o)
      {
        return (object) ((NearbyBanditBaseIssueBehavior.NearbyBanditBaseIssue) o)._targetHideout;
      }

      internal static object AutoGeneratedGetMemberValue_issueSettlement(object o)
      {
        return (object) ((NearbyBanditBaseIssueBehavior.NearbyBanditBaseIssue) o)._issueSettlement;
      }

      public override IssueBase.AlternativeSolutionScaleFlag AlternativeSolutionScaleFlags
      {
        get
        {
          return IssueBase.AlternativeSolutionScaleFlag.Casualties | IssueBase.AlternativeSolutionScaleFlag.FailureRisk;
        }
      }

      public override int AlternativeSolutionBaseNeededMenCount => 10;

      protected override int AlternativeSolutionBaseDurationInDaysInternal
      {
        get => 4 + MathF.Ceiling(6f * this.IssueDifficultyMultiplier);
      }

      protected override int RewardGold => 3000;

      internal Settlement TargetHideout => this._targetHideout;

      public override TextObject IssueBriefByIssueGiver
      {
        get
        {
          return new TextObject("{=vw2Q9jJH}Yes... There's this old ruin, a place that offers a good view of the roads, and is yet hard to reach. Needless to say, it attracts bandits. A new gang has moved in and they have been giving hell to the caravans and travellers passing by.[ib:closed][if:convo_undecided_open]");
        }
      }

      public override TextObject IssueAcceptByPlayer
      {
        get => new TextObject("{=IqH0jFdK}So you need someone to deal with these bastards?");
      }

      public override TextObject IssueQuestSolutionExplanationByIssueGiver
      {
        get
        {
          return new TextObject("{=zstiYI49}Any bandits there can easily spot and evade a large army moving against them, but if you can enter the hideout with a small group of determined warriors you can catch them unaware.[ib:closed][if:convo_thinking]");
        }
      }

      public override TextObject IssueQuestSolutionAcceptByPlayer
      {
        get => new TextObject("{=uhYprSnG}I will go to the hideout myself and ambush the bandits.");
      }

      protected override int CompanionSkillRewardXP
      {
        get => (int) (1000.0 + 1250.0 * (double) this.IssueDifficultyMultiplier);
      }

      public override bool CanBeCompletedByAI()
      {
        return Hero.MainHero.PartyBelongedToAsPrisoner != this._targetHideout.Party;
      }

      public override TextObject IssueAlternativeSolutionAcceptByPlayer
      {
        get
        {
          TextObject solutionAcceptByPlayer = new TextObject("{=IFasMslv}I will assign a companion with {TROOP_COUNT} good men for {RETURN_DAYS} days.");
          solutionAcceptByPlayer.SetTextVariable("TROOP_COUNT", this.GetTotalAlternativeSolutionNeededMenCount());
          solutionAcceptByPlayer.SetTextVariable("RETURN_DAYS", this.GetTotalAlternativeSolutionDurationInDays());
          return solutionAcceptByPlayer;
        }
      }

      public override TextObject IssueDiscussAlternativeSolution
      {
        get
        {
          return new TextObject("{=DgVU7owN}I pray for your warriors. The people here will be very glad to hear of their success.[ib:hip][if:convo_excited]");
        }
      }

      public override TextObject IssueAlternativeSolutionResponseByIssueGiver
      {
        get
        {
          TextObject parent = new TextObject("{=aXOgAKfj}Thank you, {?PLAYER.GENDER}madam{?}sir{\\?}. I hope your people will be successful.[ib:hip][if:convo_excited]");
          StringHelpers.SetCharacterProperties("PLAYER", Hero.MainHero.CharacterObject, parent);
          return parent;
        }
      }

      public override TextObject IssueAlternativeSolutionExplanationByIssueGiver
      {
        get
        {
          TextObject explanationByIssueGiver = new TextObject("{=VNXgZ8mt}Alternatively, if you can assign a companion with {TROOP_COUNT} or so men to this task, they can do the job.[ib:closed][if:convo_undecided_open]");
          explanationByIssueGiver.SetTextVariable("TROOP_COUNT", this.GetTotalAlternativeSolutionNeededMenCount());
          return explanationByIssueGiver;
        }
      }

      public override TextObject IssueAsRumorInSettlement
      {
        get
        {
          TextObject parent = new TextObject("{=ctgihUte}I hope {QUEST_GIVER.NAME} has a plan to get rid of those bandits.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.IssueOwner.CharacterObject, parent);
          return parent;
        }
      }

      public override bool IsThereAlternativeSolution => true;

      protected override TextObject AlternativeSolutionStartLog
      {
        get
        {
          TextObject parent = new TextObject("{=G4kpabSf}{ISSUE_GIVER.LINK}, a headman from {ISSUE_SETTLEMENT}, has told you about recent bandit attacks on local villagers and asked you to clear out the outlaws' hideout. You asked {COMPANION.LINK} to take {TROOP_COUNT} of your best men to go and take care of it. They should report back to you in {RETURN_DAYS} days.");
          StringHelpers.SetCharacterProperties("PLAYER", Hero.MainHero.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("ISSUE_GIVER", this.IssueOwner.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("COMPANION", this.AlternativeSolutionHero.CharacterObject, parent);
          parent.SetTextVariable("ISSUE_SETTLEMENT", this._issueSettlement.EncyclopediaLinkWithName);
          parent.SetTextVariable("TROOP_COUNT", this.AlternativeSolutionSentTroops.TotalManCount - 1);
          parent.SetTextVariable("RETURN_DAYS", this.GetTotalAlternativeSolutionDurationInDays());
          return parent;
        }
      }

      public override bool IsThereLordSolution => false;

      public override TextObject Title
      {
        get
        {
          TextObject title = new TextObject("{=ENYbLO8r}Bandit Base Near {SETTLEMENT}");
          title.SetTextVariable("SETTLEMENT", this._issueSettlement.Name);
          return title;
        }
      }

      public override TextObject Description
      {
        get
        {
          TextObject parent = new TextObject("{=vZ01a4cG}{QUEST_GIVER.LINK} wants you to clear the hideout that attracts more bandits to {?QUEST_GIVER.GENDER}her{?}his{\\?} region.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.IssueOwner.CharacterObject, parent);
          return parent;
        }
      }

      public override TextObject IssueAlternativeSolutionSuccessLog
      {
        get
        {
          TextObject parent = new TextObject("{=SN3pjZiK}You received a message from {QUEST_GIVER.LINK}.\n\"Thank you for clearing out that bandits' nest. Please accept these {REWARD}{GOLD_ICON} denars with our gratitude.\"");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.IssueOwner.CharacterObject, parent);
          parent.SetTextVariable("REWARD", this.RewardGold);
          parent.SetTextVariable("GOLD_ICON", "{=!}<img src=\"General\\Icons\\Coin@2x\" extend=\"8\">");
          return parent;
        }
      }

      public override TextObject IssueAlternativeSolutionFailLog
      {
        get
        {
          TextObject parent = new TextObject("{=qsMnnfQ3}You failed to clear the hideout in time to prevent further attacks. {QUEST_GIVER.LINK} is disappointed.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.IssueOwner.CharacterObject, parent);
          return parent;
        }
      }

      protected override bool IssueQuestCanBeDuplicated => false;

      public NearbyBanditBaseIssue(Hero issueOwner, Settlement targetHideout)
        : base(issueOwner, CampaignTime.DaysFromNow(15f))
      {
        this._targetHideout = targetHideout;
      }

      protected override float GetIssueEffectAmountInternal(IssueEffect issueEffect)
      {
        if (issueEffect == DefaultIssueEffects.SettlementProsperity)
          return -0.2f;
        return issueEffect == DefaultIssueEffects.SettlementSecurity ? -1f : 0.0f;
      }

      public override (SkillObject, int) GetAlternativeSolutionSkill(Hero hero)
      {
        int skillValue1 = hero.GetSkillValue(DefaultSkills.OneHanded);
        int skillValue2 = hero.GetSkillValue(DefaultSkills.TwoHanded);
        int skillValue3 = hero.GetSkillValue(DefaultSkills.Polearm);
        return skillValue1 >= skillValue2 && skillValue1 >= skillValue3 ? (DefaultSkills.OneHanded, 120) : (skillValue2 >= skillValue3 ? DefaultSkills.TwoHanded : DefaultSkills.Polearm, 120);
      }

      protected override void AfterIssueCreation()
      {
        this._issueSettlement = this.IssueOwner.CurrentSettlement;
      }

      public override bool DoTroopsSatisfyAlternativeSolution(
        TroopRoster troopRoster,
        out TextObject explanation)
      {
        explanation = TextObject.Empty;
        return QuestHelper.CheckRosterForAlternativeSolution(troopRoster, this.GetTotalAlternativeSolutionNeededMenCount(), ref explanation, 2);
      }

      public override bool IsTroopTypeNeededByAlternativeSolution(CharacterObject character)
      {
        return character.Tier >= 2;
      }

      public override bool AlternativeSolutionCondition(out TextObject explanation)
      {
        explanation = TextObject.Empty;
        return QuestHelper.CheckRosterForAlternativeSolution(MobileParty.MainParty.MemberRoster, this.GetTotalAlternativeSolutionNeededMenCount(), ref explanation, 2);
      }

      protected override void AlternativeSolutionEndWithSuccessConsequence()
      {
        this.RelationshipChangeWithIssueOwner = 5;
        this.IssueOwner.AddPower(5f);
        this._issueSettlement.Village.Bound.Town.Prosperity += 10f;
        TraitLevelingHelper.OnIssueSolvedThroughAlternativeSolution(this.IssueOwner, new Tuple<TraitObject, int>[1]
        {
          new Tuple<TraitObject, int>(DefaultTraits.Honor, 50)
        });
        GainRenownAction.Apply(Hero.MainHero, 1f);
      }

      protected override void AlternativeSolutionEndWithFailureConsequence()
      {
        this.RelationshipChangeWithIssueOwner = -5;
        this.IssueOwner.AddPower(-5f);
        this._issueSettlement.Village.Bound.Town.Prosperity += -10f;
      }

      protected override void OnGameLoad()
      {
      }

      protected override void HourlyTick()
      {
      }

      protected override QuestBase GenerateIssueQuest(string questId)
      {
        return (QuestBase) new NearbyBanditBaseIssueBehavior.NearbyBanditBaseIssueQuest(questId, this.IssueOwner, this._targetHideout, this._issueSettlement, this.RewardGold, CampaignTime.DaysFromNow(30f));
      }

      public override IssueBase.IssueFrequency GetFrequency()
      {
        return IssueBase.IssueFrequency.VeryCommon;
      }

      protected override bool CanPlayerTakeQuestConditions(
        Hero issueGiver,
        out IssueBase.PreconditionFlags flags,
        out Hero relationHero,
        out SkillObject skill)
      {
        flags = IssueBase.PreconditionFlags.None;
        relationHero = (Hero) null;
        skill = (SkillObject) null;
        if ((double) issueGiver.GetRelationWithPlayer() < -10.0)
        {
          flags |= IssueBase.PreconditionFlags.Relation;
          relationHero = issueGiver;
        }
        if (FactionManager.IsAtWarAgainstFaction(issueGiver.MapFaction, Hero.MainHero.MapFaction))
          flags |= IssueBase.PreconditionFlags.AtWar;
        return flags == IssueBase.PreconditionFlags.None;
      }

      public override bool IssueStayAliveConditions()
      {
        return this._targetHideout.Hideout.IsInfested && this.IssueOwner.CurrentSettlement.IsVillage && !this.IssueOwner.CurrentSettlement.IsRaided && !this.IssueOwner.CurrentSettlement.IsUnderRaid && (double) this.IssueOwner.CurrentSettlement.Village.Bound.Town.Security <= 80.0;
      }

      protected override void CompleteIssueWithTimedOutConsequences()
      {
      }
    }

    public class NearbyBanditBaseIssueQuest : QuestBase
    {
      private const int QuestGiverRelationBonus = 5;
      private const int QuestGiverRelationPenalty = -5;
      private const int QuestGiverPowerBonus = 5;
      private const int QuestGiverPowerPenalty = -5;
      private const int TownProsperityBonus = 10;
      private const int TownProsperityPenalty = -10;
      private const int TownSecurityPenalty = -5;
      private const int QuestGuid = 1056731;
      [SaveableField(100)]
      private readonly Settlement _targetHideout;
      [SaveableField(101)]
      private readonly Settlement _questSettlement;

      internal static void AutoGeneratedStaticCollectObjectsNearbyBanditBaseIssueQuest(
        object o,
        List<object> collectedObjects)
      {
        ((MBObjectBase) o).AutoGeneratedInstanceCollectObjects(collectedObjects);
      }

      protected override void AutoGeneratedInstanceCollectObjects(List<object> collectedObjects)
      {
        base.AutoGeneratedInstanceCollectObjects(collectedObjects);
        collectedObjects.Add((object) this._targetHideout);
        collectedObjects.Add((object) this._questSettlement);
      }

      internal static object AutoGeneratedGetMemberValue_targetHideout(object o)
      {
        return (object) ((NearbyBanditBaseIssueBehavior.NearbyBanditBaseIssueQuest) o)._targetHideout;
      }

      internal static object AutoGeneratedGetMemberValue_questSettlement(object o)
      {
        return (object) ((NearbyBanditBaseIssueBehavior.NearbyBanditBaseIssueQuest) o)._questSettlement;
      }

      public override TextObject Title
      {
        get
        {
          TextObject title = new TextObject("{=ENYbLO8r}Bandit Base Near {SETTLEMENT}");
          title.SetTextVariable("SETTLEMENT", this._questSettlement.Name);
          return title;
        }
      }

      public override bool IsRemainingTimeHidden => false;

      private TextObject _onQuestStartedLogText
      {
        get
        {
          TextObject parent = new TextObject("{=ogsh3V6G}{QUEST_GIVER.LINK}, a headman from {QUEST_SETTLEMENT}, has told you about the hideout of some bandits who have recently been attacking local villagers. You told {?QUEST_GIVER.GENDER}her{?}him{\\?} that you will take care of the situation yourself. {QUEST_GIVER.LINK} also marked the location of the hideout on your map.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          parent.SetTextVariable("QUEST_SETTLEMENT", this._questSettlement.EncyclopediaLinkWithName);
          return parent;
        }
      }

      private TextObject _onQuestSucceededLogText
      {
        get
        {
          TextObject parent = new TextObject("{=SN3pjZiK}You received a message from {QUEST_GIVER.LINK}.\n\"Thank you for clearing out that bandits' nest. Please accept these {REWARD}{GOLD_ICON} denars with our gratitude.\"");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          parent.SetTextVariable("REWARD", this.RewardGold);
          parent.SetTextVariable("GOLD_ICON", "{=!}<img src=\"General\\Icons\\Coin@2x\" extend=\"8\">");
          return parent;
        }
      }

      private TextObject _onQuestFailedLogText
      {
        get
        {
          TextObject parent = new TextObject("{=qsMnnfQ3}You failed to clear the hideout in time to prevent further attacks. {QUEST_GIVER.LINK} is disappointed.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject _onQuestCanceledLogText
      {
        get
        {
          TextObject parent = new TextObject("{=4Bub0GY6}Hideout was cleared by someone else. Your agreement with {QUEST_GIVER.LINK} is canceled.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      public NearbyBanditBaseIssueQuest(
        string questId,
        Hero questGiver,
        Settlement targetHideout,
        Settlement questSettlement,
        int rewardGold,
        CampaignTime duration)
        : base(questId, questGiver, duration, rewardGold)
      {
        this._targetHideout = targetHideout;
        this._questSettlement = questSettlement;
        this.SetDialogs();
        this.InitializeQuestOnCreation();
      }

      protected override void InitializeQuestOnGameLoad() => this.SetDialogs();

      protected override void HourlyTick()
      {
      }

      protected override void SetDialogs()
      {
        this.OfferDialogFlow = DialogFlow.CreateDialogFlow("issue_classic_quest_start").NpcLine("{=spj8bYVo}Good! I'll mark the hideout for you on a map.[if:convo_excited]").Condition((ConversationSentence.OnConditionDelegate) (() => Hero.OneToOneConversationHero == this.QuestGiver)).Consequence(new ConversationSentence.OnConsequenceDelegate(this.OnQuestAccepted)).CloseDialog();
        this.DiscussDialogFlow = DialogFlow.CreateDialogFlow("quest_discuss").NpcLine("{=l9wYpIuV}Any news? Have you managed to clear out the hideout yet?[if:convo_astonished]").Condition((ConversationSentence.OnConditionDelegate) (() => Hero.OneToOneConversationHero == this.QuestGiver)).BeginPlayerOptions().PlayerOption("{=wErSpkjy}I'm still working on it.").NpcLine("{=XTt6gZ7h}Do make haste, if you can. As long as those bandits are up there, no traveller is safe![if:convo_grave]").CloseDialog().PlayerOption("{=I8raOMRH}Sorry. No progress yet.").NpcLine("{=kWruAXaF}Well... You know as long as those bandits remain there, no traveller is safe.[if:convo_grave]").CloseDialog().EndPlayerOptions().CloseDialog();
      }

      private void OnQuestAccepted()
      {
        this.StartQuest();
        this._targetHideout.Hideout.IsSpotted = true;
        this._targetHideout.IsVisible = true;
        this.AddTrackedObject((ITrackableCampaignObject) this._targetHideout);
        QuestHelper.AddMapArrowFromPointToTarget(new TextObject("{=xpsQyPaV}Direction to Bandits"), this._questSettlement.Position2D, this._targetHideout.Position2D, 5f, 0.1f);
        TextObject textObject = new TextObject("{=XGa8MkbJ}{QUEST_GIVER.NAME} has marked the hideout on your map");
        StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, textObject);
        MBInformationManager.AddQuickInformation(textObject);
        this.AddLog(this._onQuestStartedLogText);
      }

      private void OnQuestSucceeded()
      {
        this.AddLog(this._onQuestSucceededLogText);
        GiveGoldAction.ApplyBetweenCharacters((Hero) null, Hero.MainHero, this.RewardGold);
        GainRenownAction.Apply(Hero.MainHero, 1f);
        TraitLevelingHelper.OnIssueSolvedThroughQuest(this.QuestGiver, new Tuple<TraitObject, int>[1]
        {
          new Tuple<TraitObject, int>(DefaultTraits.Honor, 50)
        });
        this.QuestGiver.AddPower(5f);
        this.RelationshipChangeWithQuestGiver = 5;
        this._questSettlement.Village.Bound.Town.Prosperity += 10f;
        this.CompleteQuestWithSuccess();
      }

      private void OnQuestFailed(bool isTimedOut)
      {
        this.AddLog(this._onQuestFailedLogText);
        this.RelationshipChangeWithQuestGiver = -5;
        this.QuestGiver.AddPower(-5f);
        this._questSettlement.Village.Bound.Town.Prosperity += -10f;
        this._questSettlement.Village.Bound.Town.Security += -5f;
        if (isTimedOut)
          return;
        this.CompleteQuestWithFail();
      }

      private void OnQuestCanceled()
      {
        this.AddLog(this._onQuestCanceledLogText);
        this.CompleteQuestWithFail();
      }

      protected override void OnTimedOut() => this.OnQuestFailed(true);

      protected override void RegisterEvents()
      {
        CampaignEvents.MapEventEnded.AddNonSerializedListener((object) this, new Action<MapEvent>(this.OnMapEventEnded));
        CampaignEvents.OnHideoutDeactivatedEvent.AddNonSerializedListener((object) this, new Action<Settlement>(this.OnHideoutCleared));
        CampaignEvents.MapEventStarted.AddNonSerializedListener((object) this, new Action<MapEvent, PartyBase, PartyBase>(this.OnMapEventStarted));
      }

      private void OnMapEventStarted(
        MapEvent mapEvent,
        PartyBase attackerParty,
        PartyBase defenderParty)
      {
        if (!QuestHelper.CheckMinorMajorCoercion((QuestBase) this, mapEvent, attackerParty))
          return;
        QuestHelper.ApplyGenericMinorMajorCoercionConsequences((QuestBase) this, mapEvent);
      }

      private void OnHideoutCleared(Settlement hideout)
      {
        if (this._targetHideout != hideout)
          return;
        this.CompleteQuestWithCancel();
      }

      private void OnMapEventEnded(MapEvent mapEvent)
      {
        if (!mapEvent.IsHideoutBattle || mapEvent.MapEventSettlement != this._targetHideout)
          return;
        if (mapEvent.InvolvedParties.Contains<PartyBase>(PartyBase.MainParty))
        {
          if (mapEvent.BattleState == BattleState.DefenderVictory)
          {
            this.OnQuestFailed(false);
          }
          else
          {
            if (mapEvent.BattleState != BattleState.AttackerVictory)
              return;
            this.OnQuestSucceeded();
          }
        }
        else
        {
          if (mapEvent.BattleState != BattleState.AttackerVictory)
            return;
          this.OnQuestCanceled();
        }
      }
    }

    public class NearbyBanditBaseIssueTypeDefiner : SaveableTypeDefiner
    {
      public NearbyBanditBaseIssueTypeDefiner()
        : base(400000)
      {
      }

      protected override void DefineClassTypes()
      {
        this.AddClassDefinition(typeof (NearbyBanditBaseIssueBehavior.NearbyBanditBaseIssue), 1);
        this.AddClassDefinition(typeof (NearbyBanditBaseIssueBehavior.NearbyBanditBaseIssueQuest), 2);
      }
    }
  }
}
